<template>
  <div>
    <!-- 面包屑 -->
    <bread></bread>
    <!-- 页面区域 -->
    <el-card class="box-card">
      <el-button type="primary" @click="eflag = true">添加角色</el-button>
      <el-table :data="tableData" stripe style="width: 100%" border>
        <el-table-column width="50" type="expand">
          <!-- 三级展开列 -->
          <template v-slot="scope">
            <el-row
              v-for="(item, i1) in scope.row.children"
              :key="item.id"
              :class="['bottomb', i1 === 0 ? 'topb' : '']"
            >
              <!-- 一级权限 -->
              <el-col :span="5" align="middle">
                <el-tag closable @close="removeLc(scope.row,item.id)">
                  {{ item.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item1, i2) in item.children"
                  :key="item1.id"
                  :class="[i2 === 0 ? '' : 'topb']"
                  
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="4" >
                    <el-tag type="success" closable @close="removeLc(scope.row,item1.id)">
                      {{ item1.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="(item2) in item1.children"
                      :key="item2.id"
                      type="warning"
                      closable
                      @close="removeLc(scope.row,item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <pre>
            </pre>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="50"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column prop="desc" label="操作">
          <template v-slot="scope">
            <!-- 编辑 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="redactd(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除 -->
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deldate(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配权限 -->
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-star-off"
              @click="allocation(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 编辑框 -->
      <el-dialog title="修改角色" :visible.sync="flag" width="30%">
        <el-form :model="backfills" :rules="rules" ref="ruleForm" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="backfills.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="backfills.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="flag = false">取 消</el-button>
          <el-button type="primary" @click="redactdate(backfills)">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加框 -->
      <el-dialog title="添加角色" :visible.sync="eflag" width="30%">
        <el-form :model="backfills" :rules="rules" ref="ruleForm" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="backfills.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="backfills.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="eflag = false">取 消</el-button>
          <el-button type="primary" @click="addDate(backfills)">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限 -->
      <el-dialog title="分配权限" :visible.sync="flagone" width="30%" @close="setdata">
        <!-- 树形控件 -->
        <el-tree
          :data="treedata"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="deforkeys"
          ref="treeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="flagone = false">取 消</el-button>
          <el-button type="primary" @click="powerOk()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import bread from "../bread";
export default {
  components: { bread },
  name: "",
  data() {
    return {
      tableData: [], //页面数据
      flag: false, //编辑框变量
      backfills: {}, //回填数据
      eflag: false, //添加框变量
      flagone: false, //分配权限变量
      treedata: [], //树形结构数据
      deforkeys: [], //默认选中的权限数组
      roleId: "", //即将分配权限的id
      rulefo: {
        roleName: "",
        roleDesc: "",
      },
      rules: {
        roleName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        roleDesc: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      },
      //数形绑定
      defaultProps: {
        children: "children",
        label: "authName",
      },
    };
  },
  mounted() {
    this.rolist();
  },
  methods: {
    // 请求角色列表信息
    async rolist() {
      const { data: res } = await this.$axios.get("roles");
      this.tableData = res;
    },

    //删除
    async deldate(obj) {
      const res = await this.$axios.delete(`roles/${obj}`);
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      } else {
        this.$message.success(res.meta.msg);
        this.rolist(); //重新调用页面信息
      }
    },

    //编辑-数据回填
    async redactd(obj) {
      this.flag = true;
      const res = await this.$axios.get(`roles/${obj}`);

      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      } else {
        this.backfills = res.data;
      }
    },

    //编辑-提交数据
    async redactdate(backfills) {
      this.flag = false;
      const res = await this.$axios.put(`roles/${backfills.roleId}`, this.backfills);
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg);
      } else {
        this.$message.success("修改数据成功");
        this.rolist();
      }
    },

    //添加
    async addDate(backfills) {
      this.eflag = false;
      const res = await this.$axios.post("roles", this.backfills);
      if (res.meta.status !== 201) {
        this.$message.error(res.meta.msg);
      } else {
        this.$message.success(res.meta.msg);
        this.rolist();
      }
    },

    //分配权限-递归判断节点
    allocat(node, arr) {
      // node节点不包括children
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.allocat(item, arr);
      });
    },

    //分配权限
    async allocation(role) {
      this.roleId = role.id;
      const res = await this.$axios.get(`rights/tree`);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取数据失败");
      }
      this.treedata = res.data;

      //递归获取当前的节点
      this.allocat(role, this.deforkeys);

      this.flagone = true;
    },

    //分配权限-监听关闭事件重新赋值
    setdata() {
      this.deforkeys = [];
    },

    //提交权限
    async powerOk() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");

      const res = await this.$axios.post(`roles/${this.roleId}/rights`, {
        rids: idStr,
      });

      if (res.meta.status !== 200) {
        this.$message.error("分配权限失败");
      }
      this.$message.success("分配权限成功");
      this.rolist();
      this.flagone = false;
    },

    //删除单个权限
    removeLc(rol,rightId){
      console.log(rol);
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
            const res = await this.$axios.delete(`roles/${rol.id}/rights/${rightId}`);
            console.log(res);
            if(res.meta.status !==200){
              return this.$message.error('删除权限失败')
            }else{
            this.$message.success('取消权限成功')
            rol.children = res.data
            }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      
    }
  },
  computed: {},
  watch: {},
};
</script>

<style lang="scss" scoped>
.el-tag {
  margin: 6px;
}
.bottomb {
  border-bottom: 1px solid rgb(230, 230, 230);
}
.topb {
  border-top: 1px solid rgb(230, 230, 230);
}
</style>